package com.ccit.order.controller;

import com.ccit.common.client.AreaClient;
import com.ccit.common.client.IntegralClient;
import com.ccit.common.client.MoneyClient;
import com.ccit.common.exception.GymException;
import com.ccit.common.result.Result;
import com.ccit.common.utils.PageUtil;
import com.ccit.common.utils.RedisUtils;
import com.ccit.model.Integral;
import com.ccit.model.Order;
import com.ccit.model.vo.money.MoneyVo;
import com.ccit.model.vo.order.OrderVo;
import com.ccit.order.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Api(tags = "柜台入场订单")
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    RedisUtils redisUtils;

    @Autowired
    OrderService orderService;

    @Autowired
    IntegralClient integralClient;

    @Autowired
    private MoneyClient moneyClient;

    @Autowired
    AreaClient areaClientService;


    @GetMapping("/getByPage/{current}/{limit}")
    @ApiOperation(value = "历史订单查询(分页)")
    public Result findOrder(@PathVariable("current") Integer current,
                            @PathVariable("limit") Integer limit) {
        List orderList;
        boolean has = redisUtils.hasKey("areaOrderList");
        if (has) {
            orderList =  (List<Order>) redisUtils.get("areaOrderList");
        } else {
            orderList = orderService.findAllOrder();
            redisUtils.set("areaOrderList",orderList);
        }
        com.baomidou.mybatisplus.extension.plugins.pagination.Page pages = PageUtil.getPages(current, limit, orderList);
        return Result.ok(pages);
    }

    @GetMapping("/getYear")
    @ApiOperation(value = "查询5年之前订单")
    public Result getYear() {
        List orderVos = new ArrayList<>();
        boolean has = redisUtils.hasKey("areaOrderYear");
        if (has){
            orderVos =(List<Order>) redisUtils.get("areaOrderYear");
        }else {
            String[] split = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString().split("-");
            //遍历
            for (int i = Integer.valueOf(split[0]) + 1; i > Integer.valueOf(split[0]) - 5; i--) {
                OrderVo orderVo = new OrderVo();
                orderVo.setDate(Integer.toString(i - 1) + "年");
                try {
                    Date startTime = new SimpleDateFormat("yyyy-MM-dd").parse(i - 1 + "-00-00");
                    Date endTime = new SimpleDateFormat("yyyy-MM-dd").parse(i + "-00-00");

                    List<Order> orderList = orderService.findOrderByTime(startTime, endTime);
                    if (orderList.size() != 0) {
                        orderVo.setCount(orderList.size());
                    } else orderVo.setCount(0);
                    orderVos.add(orderVo);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            //存入redis
            redisUtils.set("areaOrderYear",orderVos);
        }

        return Result.ok(orderVos);
    }

    @GetMapping("/getMonth")
    @ApiOperation(value = "查询过去半年每月订单")
    public Result getMonth() {
        List orderVos = new ArrayList<>();
        boolean has = redisUtils.hasKey("areaOrderMonth");
        if (has){
            orderVos = (List<Order>)redisUtils.get("areaOrderMonth");
        }else {
            String[] split = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString().split("-");

            if (Integer.valueOf(split[1]) - 6 >= 0) {
                for (int i = Integer.valueOf(split[1]) + 1; i > Integer.valueOf(split[1]) - 5; i--) {
                    OrderVo orderVo = new OrderVo();
                    orderVo.setDate(split[0] + "年" + Integer.toString(i - 1) + "月");

                    try {
                        Date startTime = new SimpleDateFormat("yyyy-MM-dd").parse(Integer.valueOf(split[0]) + "-" + (i - 1) + "-00");
                        Date endTime = new SimpleDateFormat("yyyy-MM-dd").parse(Integer.valueOf(split[0]) + "-" + i + "-00");

                        List<Order> orderList = orderService.findOrderByTime(startTime, endTime);
                        System.out.println(orderList + "-------------------------"+(i-1));
                        if (orderList.size() != 0) {
                            orderVo.setCount(orderList.size());
                        } else orderVo.setCount(0);
                        orderVos.add(orderVo);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                for (int i = Integer.valueOf(split[1]) + 1; i > 0; i--) {
                    OrderVo orderVo = new OrderVo();
                    orderVo.setDate(split[0] + "年" + Integer.toString(i - 1) + "月");

                    try {
                        Date startTime = new SimpleDateFormat("yyyy-MM-dd").parse(Integer.valueOf(split[0]) + "-" + (i - 1) + "-00");
                        Date endTime = new SimpleDateFormat("yyyy-MM-dd").parse(Integer.valueOf(split[0]) + "-" + i + "-00");

                        List<Order> orderList = orderService.findOrderByTime(startTime, endTime);
                        System.out.println(orderList + "-------------------------");
                        if (orderList.size() != 0) {
                            orderVo.setCount(orderList.size());
                        } else orderVo.setCount(0);
                        orderVos.add(orderVo);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                for (int i = 12; i >= 12 + Integer.valueOf(split[1]) - 5; i--) {
                    OrderVo orderVo = new OrderVo();
                    orderVo.setDate(Integer.valueOf(split[0]) - 1 + "年" + Integer.toString(i - 1) + "月");

                    try {
                        Date startTime = new SimpleDateFormat("yyyy-MM-dd").parse(Integer.valueOf(split[0]) - 1 + "-" + (i - 1) + "-00");
                        Date endTime = new SimpleDateFormat("yyyy-MM-dd").parse(Integer.valueOf(split[0]) - 1 + "-" + i + "-00");

                        List<Order> orderList = orderService.findOrderByTime(startTime, endTime);
                        System.out.println(orderList + "-------------------------");
                        if (orderList.size() != 0) {
                            orderVo.setCount(orderList.size());
                        } else orderVo.setCount(0);
                        orderVos.add(orderVo);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
            //存入redis
            redisUtils.set("areaOrderMonth",orderVos,600000);
        }

        return Result.ok(orderVos);
    }

    @GetMapping("/getAreaRate")
    @ApiOperation(value = "查询过去时间(默认今年)订单场地占比")
    public Result getAreaRate(@RequestParam(required = false) Integer year,@RequestParam(required = false) Integer month) {
        String key = "areaOrderRate";
        String[] split = new SimpleDateFormat("yyyy-MM-dd").format(new Date()).toString().split("-");
        if (year != null){
            split[0] = Integer.toString(year);
            key = key + ":" +year;
        }
        if (month != null){
            split[1] = Integer.toString(month);
            key = key + ":" + month;
        }

        List orderVoList ;
        boolean has = redisUtils.hasKey(key);
        if (has){
            orderVoList = (List<Order>) redisUtils.get("areaOrderRate");
            return Result.ok(orderVoList);
        }else {
            try {
                Date startTime = new SimpleDateFormat("yyyy-MM-dd").parse(split[0] + "-00-00");
                Date endTime = new SimpleDateFormat("yyyy-MM-dd").parse(split[0] +"-"+ Integer.valueOf(split[1])+1  +"-00");

                List<Order> list = orderService.findOrderByTime(startTime, endTime);
                Map<String,List<Order>> orderMaps = new HashMap<>();
                list.forEach(order -> {
                    List<Order> orderList=new ArrayList<>();
                    if (orderMaps.get(order.getArea())!=null){
                        orderList = orderMaps.get(order.getArea());
                    }
                    orderList.add(order);
                    orderMaps.put(order.getArea(),orderList);
                });
                orderVoList = new ArrayList<>();
                orderMaps.forEach((s, orders) -> {
                    OrderVo orderVo = new OrderVo();
                    orderVo.setDate(split[0]+"-"+split[1]);
                    orderVo.setArea(s);
                    orderVo.setAreaRate((double)orders.size()/list.size());
                    orderVoList.add(orderVo);
                });
                Map<String,Integer> ordersMaps = new HashMap<>();
                orderMaps.forEach((s, orders) -> {
                    ordersMaps.put(s,orders.size());
                });
                redisUtils.set(key, orderVoList, 600000);
                return Result.ok(orderVoList);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
        return Result.fail();
    }


    @GetMapping("/getByPage/{current}/{size}/{phone}")
    @ApiOperation(value = "根据手机号查询订单(分页)")
    public Result selectOrderByPhone(@PathVariable("current") Integer current,
                                     @PathVariable("size") Integer size,
                                     @PathVariable("phone") String phone) {
        List<Order> orderByPhone;
        String key = "areaOrderByPhone"+":"+phone + ":" + current + ":" + size;
        boolean has = redisUtils.hasKey(key);
        if (has){
             orderByPhone = (List<Order>) redisUtils.get(key);
        }else {
            orderByPhone = orderService.findOrderByPhone(phone);
            if (orderByPhone==null){
                throw new GymException(202,"无此手机用户");
            }
            redisUtils.set(key,orderByPhone);
        }
        com.baomidou.mybatisplus.extension.plugins.pagination.Page pages = PageUtil.getPages(current, size, orderByPhone);
        return Result.ok(pages);
    }


    @ApiOperation(value = "添加新订单")
    @PostMapping("/saveOrder/{num}")
    public Result saveOrder(@RequestBody Order order, @PathVariable Integer num) {
        orderService.saveNewOrder(order, num);
        Integral integral = new Integral();
        integral.setIntegral((int)(Math.round(order.getPrice()*num/100)));
        integral.setPhone(order.getPhone());
        System.out.println(integral);
        Boolean b = integralClient.updateIntegral(integral);
        if (!b){
            throw new GymException(202,"更新积分出错");
        }
        boolean flag = areaClientService.updateAreaPersonNumByName(order.getArea(), num);
        if (flag){
            MoneyVo moneyVo = new MoneyVo();
            moneyVo.setMoneyType("收入");
            moneyVo.setTypeName("区域订单");
            moneyVo.setAmout(order.getPrice());
            boolean b1 = moneyClient.apiSaveMoney(moneyVo);
            if (!b1){
                throw new GymException(301,"添加区域订单资金记录失败");
            }
            redisUtils.deleteRedisKeys("areaOrder");
            redisUtils.deleteRedisKeys("orderListByPage");
            redisUtils.deleteRedisKeys("areaOrderByPhone");
            redisUtils.deleteRedisKeys("areaOrderRate");
            redisUtils.deleteRedisKeys("areaOrderMonth");
            redisUtils.deleteRedisKeys("areaOrderYear");
            redisUtils.deleteRedisKeys("areaOrderList");
            return Result.ok();
        }
        else
            throw new GymException(202,"更新区域出错");
    }


}
